<template>
  <div class="employee-list">
    <!-- 添加顶部栏 -->
    <div class="header-bar">
      <h2>员工管理</h2>
      <div class="user-info">
        <span>欢迎您，{{ currentUser.userName }}</span>
        <el-button type="danger" link @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-button>
      </div>
    </div>

    <el-card class="table-card" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="operation-bar">
        <div class="search-section">
          <el-select
            v-model="searchDept"
            placeholder="选择部门"
            clearable
            style="width: 120px; margin-right: 10px;"
            @change="handleSearch">
            <el-option label="全部部门" value="" />
            <el-option label="管理部" value="管理部" />
            <el-option label="销售部" value="销售部" />
            <el-option label="采购部" value="采购部" />
            <el-option label="仓储部" value="仓储部" />
          </el-select>

          <el-select
            v-model="searchStatus"
            placeholder="选择状态"
            clearable
            style="width: 120px; margin-right: 10px;"
            @change="handleSearch">
            <el-option label="全部状态" value="" />
            <el-option label="在职" value="1" />
            <el-option label="离职" value="0" />
          </el-select>

          <el-input
            v-model="searchText"
            placeholder="请输入员工工号或姓名搜索"
            class="search-input"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
        </div>

        <el-button
          type="success"
          @click="handleAdd"
          v-if="currentUser.userType === 'admin'">
          <el-icon><Plus /></el-icon>新增员工
        </el-button>
      </div>

      <!-- 员工表格 -->
      <el-table
        v-loading="loading"
        :data="employeeList"
        style="width: 100%"
        border
        stripe>
        <el-table-column prop="employeeNo" label="员工工号" width="150" align="center" />
        <el-table-column prop="userName" label="姓名" width="120" align="center" />
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="sex" label="性别" width="80" align="center" />
        <el-table-column prop="deptName" label="所属部门" width="120" align="center" />
        <el-table-column prop="position" label="职位" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'" effect="plain">
              {{ scope.row.status === '1' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hireDate" label="入职日期" width="120" align="center" />
        <el-table-column prop="salary" label="薪资" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.salary">￥{{ scope.row.salary.toFixed(2) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
              v-if="currentUser.userType === 'admin'">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
              :type="scope.row.status === '1' ? 'warning' : 'success'"
              link
              @click="handleToggleStatus(scope.row)"
              v-if="currentUser.userType === 'admin'">
              <el-icon><Switch /></el-icon>{{ scope.row.status === '1' ? '离职' : '入职' }}
            </el-button>
            <el-popconfirm
              title="确定删除该员工吗？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.row)"
              v-if="currentUser.userType === 'admin'">
              <template #reference>
                <el-button type="danger" link>
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchEmployeeList"
          @current-change="fetchEmployeeList"
        />
      </div>
    </el-card>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="500px"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId" v-if="dialogType === 'add'">
          <el-input v-model="form.userId" placeholder="留空将自动使用员工工号作为用户ID" />
        </el-form-item>
        <el-form-item label="员工工号" prop="employeeNo">
          <el-input v-model="form.employeeNo" placeholder="请输入员工工号">
            <template #append>
              <el-button @click="handleGenerateNo">生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱（可选）" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话（可选）" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位" />
        </el-form-item>
        <el-form-item label="入职日期" prop="hireDate">
          <el-date-picker
            v-model="form.hireDate"
            type="date"
            placeholder="请选择入职日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, SwitchButton, Switch, Download, Upload } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getEmployeeList, createEmployee, updateEmployee, deleteEmployee, generateEmployeeNo, updateEmployeeStatus } from '@/api/employeeApi'

const router = useRouter()

// 员工列表数据
const employeeList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchText = ref('')
const searchDept = ref('')
const searchStatus = ref('')
const loading = ref(false)

// 批量操作
const selectedEmployees = ref([])

// 上传相关
const uploadRef = ref()
const uploadAction = 'http://localhost:8001/api/employees/import'
const uploadHeaders = ref({})
const uploadData = ref({})

// 获取当前登录用户信息
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

// 添加/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const form = ref({
  id: null,
  userId: '',
  employeeNo: '',
  userName: '',
  email: '',
  phone: '',
  userType: '',
  age: null,
  sex: '',
  deptName: '',
  position: '',
  hireDate: '',
  salary: null
})

// 表单校验规则
const rules = {
  employeeNo: [{ required: true, message: '请输入员工工号', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  deptName: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }]
}

// 获取员工列表
const fetchEmployeeList = async () => {
  loading.value = true
  try {
    const params = {}

    // 添加搜索条件
    if (searchText.value && searchText.value.trim()) {
      params.keyword = searchText.value.trim()
    }
    if (searchDept.value) {
      params.deptName = searchDept.value
    }
    if (searchStatus.value) {
      params.status = searchStatus.value
    }

    const res = await getEmployeeList(params)
    console.log('员工API返回数据:', res)

    if (res.code === 200 && res.data) {
      if (Array.isArray(res.data)) {
        // 过滤掉已删除（离职）的员工，只显示在职状态的员工
        const activeEmployees = res.data.filter(employee => employee.status === '1')
        employeeList.value = activeEmployees
        total.value = activeEmployees.length
      } else {
        console.error('返回数据格式不正确:', res.data)
        ElMessage.error('数据格式不正确')
      }
    } else {
      ElMessage.error(res.message || '获取员工列表失败')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  fetchEmployeeList()
}

// 打开添加对话框
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true

  // 后端返回的EmployeeVO已经包含了完整的用户信息，直接使用
  form.value = {
    ...row,
    // 确保字段映射正确
    userType: row.userType || 'employee'
  }
}

// 切换员工状态
const handleToggleStatus = async (row) => {
  // 检查权限：只有管理员可以切换员工状态
  if (currentUser.value.userType !== 'admin') {
    ElMessage.warning('只有管理员可以切换员工状态')
    return
  }

  const newStatus = row.status === '1' ? '0' : '1'
  const action = newStatus === '1' ? '入职' : '离职'

  try {
    const res = await updateEmployeeStatus(row.userId, newStatus, currentUser.value.userId)
    if (res.code === 200) {
      ElMessage.success(`${action}成功`)
      fetchEmployeeList()
    } else {
      ElMessage.error(res.message || `${action}失败`)
    }
  } catch (error) {
    console.error(`${action}失败:`, error)
    ElMessage.error(`${action}失败`)
  }
}

// 删除员工
const handleDelete = async (row) => {
  // 检查权限：只有管理员可以删除员工
  if (currentUser.value.userType !== 'admin') {
    ElMessage.warning('只有管理员可以删除员工')
    return
  }

  try {
    const res = await deleteEmployee(row.userId, currentUser.value.userId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      if (employeeList.value.length === 1 && pageNum.value > 1) {
        pageNum.value--
      }
      fetchEmployeeList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单（添加/编辑）
const handleSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (dialogType.value === 'add') {
          // 添加员工时，需要先创建用户，再创建员工

          // 1. 先创建用户（如果没有提供userId）
          let finalUserId = form.value.userId

          if (!finalUserId || finalUserId.trim() === '') {
            // 生成用户ID（使用员工工号作为用户ID）
            finalUserId = form.value.employeeNo

            const userData = {
              userId: finalUserId,
              userName: form.value.userName,
              userType: 'employee',
              email: form.value.email || '',
              phone: form.value.phone || '',
              password: '123456' // 默认密码
            }

            // 导入用户API
            const { createUser } = await import('@/api/userApi')
            const userRes = await createUser(userData, currentUser.value.userId)

            if (userRes.code !== 200) {
              ElMessage.error('用户创建失败：' + (userRes.message || '未知错误'))
              return
            }
          }

          // 2. 创建员工记录
          const employeeData = {
            userId: finalUserId,
            employeeNo: form.value.employeeNo,
            age: form.value.age,
            sex: form.value.sex,
            deptName: form.value.deptName,
            position: form.value.position,
            hireDate: form.value.hireDate,
            salary: form.value.salary
          }

          res = await createEmployee(employeeData, currentUser.value.userId)
        } else {
          // 编辑时，需要同时更新用户信息和员工信息

          // 1. 先更新用户信息（姓名）
          const userData = {
            userId: form.value.userId,
            userName: form.value.userName,
            userType: form.value.userType || 'employee', // 保持原有用户类型
            email: form.value.email,
            phone: form.value.phone
          }

          // 导入用户API
          const { updateUser } = await import('@/api/userApi')
          const userRes = await updateUser(form.value.userId, userData, currentUser.value.userId)

          if (userRes.code !== 200) {
            ElMessage.error('用户信息更新失败：' + (userRes.message || '未知错误'))
            return
          }

          // 2. 再更新员工信息
          const employeeData = {
            userId: form.value.userId,
            employeeNo: form.value.employeeNo,
            age: form.value.age,
            sex: form.value.sex,
            deptName: form.value.deptName,
            position: form.value.position,
            hireDate: form.value.hireDate,
            salary: form.value.salary
          }
          res = await updateEmployee(form.value.userId, employeeData, currentUser.value.userId)
        }

        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchEmployeeList()
        } else {
          ElMessage.error(res.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加失败:' : '更新失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    id: null,
    userId: '',
    employeeNo: '',
    userName: '',
    email: '',
    phone: '',
    userType: '',
    age: null,
    sex: '',
    deptName: '',
    position: '',
    hireDate: '',
    salary: null
  }
}

// 生成员工工号
const handleGenerateNo = async () => {
  try {
    const res = await generateEmployeeNo()
    if (res.code === 200 && res.data) {
      form.value.employeeNo = res.data
      ElMessage.success('员工工号生成成功')
    } else {
      ElMessage.error(res.message || '生成员工工号失败')
    }
  } catch (error) {
    console.error('生成员工工号失败:', error)
    ElMessage.error('生成员工工号失败')
  }
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('已退出登录')
}

// 初始化
onMounted(() => {
  fetchEmployeeList()
})
</script>

<style scoped>
.employee-list {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 60px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.header-bar h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info span {
  color: #606266;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.table-card :deep(.el-card__body) {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

:deep(.el-table) {
  border-radius: 8px 8px 0 0;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-tag) {
  min-width: 60px;
}
</style>